const router = require('express').Router()
const adminModel = require('../../models/adminModel')
const aes = require('../../common/aes')
const Jwt = require('../../common/jwt')

// 注册账号
// URL: /api/admin/register
// 示例地址: http://localhost:3000/api/admin/register
// 方式： post
// 参数： admin_name,admin_email,admin_phone,admin_pwd,admin_create_time
router.post('/register', async (req,res,next)=> {
    // 解构赋值
    let {admin_name,admin_email,admin_phone,admin_pwd} = req.body;
    console.log({admin_name,admin_email,admin_phone,admin_pwd})
    
    if(admin_name && admin_email &&  admin_phone &&  admin_pwd) {
        let date = new Date();
        let admin_create_time = date.toLocaleDateString() + " " + (date.toLocaleTimeString());
        // console.log(admin_create_time)        
        let admin_password = aes.aesEncrypt(admin_pwd);
        await adminModel.register(admin_name,admin_email,admin_phone,admin_password,admin_create_time)
        .then(
             content =>{
                res.send(content)
             },
             err=> {
                res.send(err)
             }
        )
    }
    else {
        res.send({
            code: -1,
            msg: "缺少参数。"
        })
    }
    next();
})

// 登录账号
// URL: /api/admin/login
// 示例地址: http://localhost:3000/api/admin/login
// 方式： post
// 参数： admin_email,admin_pwd
router.post('/login', async (req,res)=> {
    let {admin_email,admin_pwd} = req.body;
    if(admin_email && admin_pwd){
        await adminModel.login(admin_email)
        .then(
            data => {
                // 取出加密的admin_pwd
                if(data.admin_pwd) {
                    // console.log({x:data.admin_pwd})
                    // console.log({admin_pwd})
                    // 获取用户id
                    let id = data.id;
                    let token;
                    if(id) {
                        let jwt = new Jwt(id)
                        token = jwt.getToken()
                    }
                  
                    // console.log("生成的token:",jwt.getToken());

                    // 解密
                    let bool = aes.aesDecrypt(admin_pwd , data.admin_pwd)
                    // console.log({bool})
                    if(bool){
                        res.send({
                            code: 200,
                            msg: "登录成功",
                            login: bool,
                            admin_email,
                            token
                        })
                    }
                    else {
                        res.send({
                            code: -1,
                            msg: "登录失败,账号或密码错误",

                        })
                    }
                }
                else {
                    res.send({
                        code: 404,
                        msg:"该账号不存在"
                    })
                }
            },
            err=> {
                res.send(err)
            }
        )
    }
    else {
        res.send({
            code: -1,
            msg: "缺少参数。"
        })
    }
})


// 获取账号信息
// URL: /api/admin/info
// 示例地址: http://localhost:3000/api/admin/info
// 方式： post
// 参数： token admin_email
router.post('/info', async (req,res)=> {
    // 获取token信息（临时身份，令牌）
    let token = req.headers.token || req.body.token;
    let admin_email = req.body.admin_email;
    let result = new Jwt(token).verifyToken()
    if(result.code === 200){
        // 登录有效
        // 用户id
        let id = result.info.data;
        // console.log({id})
        await adminModel.info(id,admin_email)
        .then(
            content=> {
                res.send(content)
            },
            err=>{
                res.send(err);
            }
        )
    }
    else {
        // 登录失效
        res.send({
            code: -1,
            msg: "登录状态失效,请重新登录"
        })
    }
    
})

// 修改密码
// URL: /api/admin/findpwd
// 示例地址: http://localhost:3000/api/admin/findpwd
// 方式： post
// 参数： admin_email new_admin_pwd
router.post('/findpwd', async (req,res)=> {
    // 接收界面提交的参数
    let admin_email = req.body.admin_email;
    let new_admin_pwd = req.body.new_admin_pwd;
    // 判断参数是否有值
    if(admin_email && new_admin_pwd){
        let admin_password = aes.aesEncrypt(new_admin_pwd);
        // 找回密码
        await adminModel.findpwd(admin_email,admin_password)
        .then(
            content=> {
                res.send(content)
            },
            err=>{
                res.send(err);
            }
        )
    }
    else {
        res.send({
            code: -1,
            msg: "缺少参数。"
        })
    }
})



// 用户部分
// 用户列表
// URL: /api/admin/list_user
// 参数：token , page , pageSize
router.get('/list_user',async (req,res)=> {
    // 获取token
    let token = req.query.token || req.headers.token;
    // 验证token
    let result = new Jwt(token).verifyToken();
    if (result.code == 200) {
        let {page , pageSize} = req.query;
        // 分页列表
        await adminModel.list_user(page , pageSize)
        .then(
            (content)=>{
                res.send(content)
            },
            (error)=>{
                res.send(error)
            }
        )
    }
    else {
        res.send({
            code: -1,
            msg: '登录失效,请重新登录。'
        })
    }
})
// 删除用户
// URL: /api/admin/remove_user
// 参数：token , user_id
router.post('/remove_user',async (req,res)=> {
    // 获取token
    let token = req.body.token || req.headers.token;
    // 验证token
    let result = new Jwt(token).verifyToken();
    if (result.code == 200) {
        let {user_id} = req.body;
        // 删除
        await adminModel.remove_user(user_id)
        .then(
            (content)=>{
                res.send(content)
            },
            (error)=>{
                res.send(error)
            }
        )
    }
    else {
        res.send({
            code: -1,
            msg: '登录失效,请重新登录。'
        })
    }
})

// 搜索用户
// URL: /api/admin/search
// 参数：keyword
router.get('/search',async (req,res)=> {
    // 获取token
    let token = req.query.token || req.headers.token;
    // 验证token
    let result = new Jwt(token).verifyToken();
    if (result.code == 200) {
        let {keyword} = req.query;
        // 删除
        await adminModel.search(keyword)
        .then(
            (content)=>{
                res.send(content)
            },
            (error)=>{
                res.send(error)
            }
        )
    }
    else {
        res.send({
            code: -1,
            msg: '登录失效,请重新登录。'
        })
    }
})


module.exports = router;